﻿var isDealer = false, groupVal = [{id:0,name:lg.group}], GFRAME = {};
//控制跟踪和回放地址以及dialog弹出窗口中JSP页面的域（兼顾CS和BS）；
var trackUrl,playbackUrl,xdmKey,jspDomain;
GFRAME.imgUrl = "../../images/";
GFRAME.leftFrameWidth = 260;
GFRAME.isCustTreeShow = false;
GFRAME.isDealer = false;
GFRAME.viewOnline = true;
GFRAME.viewOffline = true;
GFRAME.treeCustid = custid;
//数组索引
GFRAME.listKey = null;
//第一次的原始数据.地图进行切换时，可能经纬度不同导致切换后第一次的位置数据不正确，所以切换时先请求要切换的地图的位置数据
GFRAME.listData = [];
GFRAME.userList = {};
GFRAME.groupData = null;
//包含了用户列表dom  item  userDivList.U10  ...
GFRAME.userDivList = {};
//包含了组列表dom  item  userDivList.U10  ...
GFRAME.gropDivList = {};
//mapType表示url路径请求指定地图类型，currentMap表示当前使用地图
GFRAME.currentMap = mapType;
GFRAME.crllist={};//基站画圆
GFRAME.crl=null;

//初始化各种url变量，在切换地图时手动调用此方法保证访问地址的mapType与当前地图同步
(function(){
	//跟踪回放的custname是设备名称
	var tempStr = '&lang='+ lang + '&mds='+ mds + 
			'&requestSource=' + requestSource + '&custid=' + loginCustId +
			'&loginUrl=&custname=';
	xdmKey = tempStr + custname +'&locale='+('cn'==lang?'zh-cn':'en-us') ;
	//跟踪和回放地址中不包含mapType参数，需要点击时动态附加
//	if(IS_CLIENT){
//		trackUrl = 'tracking.html?v=' + _CONFIG_.CONFIG_VERSION + tempStr;
//		playbackUrl = 'playback.html?v=' + _CONFIG_.CONFIG_VERSION + tempStr;
//		jspDomain = LOGIN_SITE;
//	}else{ 
		trackUrl = 'tracking.aspx?v=1.2.1.8' + tempStr;
	    playbackUrl = 'history.aspx?v=1.2.1.8' + tempStr;
	    jspDomain = "";
//	}
})();
//设置当前选择的设备id
function setOpenId(userid){
	var mapWin = _('map_frame').contentWindow;
	if(!mapWin.GFRAME)return;
	var oldId = mapWin.GFRAME.openPopMarkerUid;
	mapWin.GFRAME.openPopMarkerUid = userid;
	return oldId;
}
//获取当前选择设备的id
function getOpenId(){
	var gf = _('map_frame').contentWindow.GFRAME;
	return gf?gf.openPopMarkerUid:gf;
}
//全部、在线、离线切换
function switchMenu(showOnline,showOffline,anchor){
	GFRAME.viewOnline = showOnline;
	GFRAME.viewOffline = showOffline;
	GFRAME.updateByMenuState(showOnline,showOffline);
	var navDiv = anchor.parentNode.parentNode.children;
	for(var i=0,len = navDiv.length;i<len;i++){
		var item =navDiv[i], className = item.className, hasOver = className.indexOf('navigate_item_over')>0, child = item.children[0];
		if( hasOver && child !=anchor){
			item.className = className.replace('navigate_item_over','');
		}else if(child == anchor && !hasOver){
			item.className += ' navigate_item_over';
		}
	}
}

function updateStateButton(){
	var _all = document.getElementById("state_button_all");
	var _online = document.getElementById("state_button_online");
	var _offline = document.getElementById("state_button_offline");
	_all.className = _online.className = _offline.className = "statemenu";
	if(GFRAME.viewOnline && GFRAME.viewOffline){
		_all.className = "statemenuover";
	}else{
		if(GFRAME.viewOnline){
			_online.className = "statemenuover";
		}else{
			_offline.className = "statemenuover";
		}
	}
}

var searchFocusTimer = null;
var isSearchFocus = false;
function searchFocus(_input){
	isSearchFocus = true;
	if(_input.value==lg.addGroupTip){
		_input.value = "";
		_input.setAttribute("presearvalue","?");
	}

	var search = function(){
		if(_input.getAttribute("presearvalue")!=_input.value){
			_input.setAttribute("presearvalue",_input.value);
			searchListOut(_input.value);
		}
		searchFocusTimer = setTimeout(search,300);
	};
	search();
}

function viewSearchListAll(){
	isSearchFocus = true;
	if(document.getElementById("searchListOutCanvas").style.display != "block"){
		searchListOut("");
	}
}

function timeHiddenSearch(){
	var hidden = function(){
		if(!isSearchFocus){
			document.getElementById("searchListOutCanvas").style.display = "none";
		}
	};
	hidden();
}

function searchBlur(_input){
	isSearchFocus = false;
	window.clearTimeout(searchFocusTimer);

	if(_input.value==""){
		_input.value = lg.addGroupTip;
	}
}
//供应商弹出层
function tipContent(e,t){
	if(t){
		st = $('#tset_item');
		var pos = $(e).offset();
		$('img',st).remove();
		$("div.tipContent").css({zIndex:500,left:pos.left+30,top: pos.top-55}).html(st.html()).show();
	}else{
		$("div.tipContent").hide();
	}
}
function searchListOut(v){
	overindex = 0;
	var _canvas = document.getElementById("searchListOutCanvas"),
		p = 0, pvalue = "", frag = document.createDocumentFragment(), listKey = GFRAME.listKey,
		len = GFRAME.listData.length;
	_canvas.innerHTML = "";
	_canvas.style.display = "block";
	_canvas.scrollTop = 0;
	for(var i=0;i<len;i++){
		if(GFRAME.listData[i][listKey.user_name].toLowerCase().indexOf(v.toLowerCase())>-1){
			p++;
			var st = GFRAME.parseRecordPOJO(GFRAME.listData[i]);
			if((st.run_status.indexOf(lg.serviceEnd[3]) > -1 || st.run_status != lg.arrear) && st.su != -9){
				pvalue = GFRAME.listData[i][listKey.user_name];
				var _div = document.createElement("div");
				frag.appendChild(_div);
				if(p==1){
					_div.className = "search_item_over";
				}else{
					_div.className = "search_item";
				}
				_div.style.cursor = "pointer";
				_div.innerHTML = GFRAME.listData[i][listKey.user_name];
				_div.setAttribute("username",GFRAME.listData[i][listKey.user_name]);
				_div.setAttribute("index",i);
				_div.setAttribute("userid",GFRAME.listData[i][listKey.user_id]);
				_div.onclick = function(){
					document.getElementById("searchListOutCanvas").style.display = "none";
					selectSearchItem(this.getAttribute("username"),this.getAttribute("userid"));
				 };
				_div.onmouseover = function(){this.className="search_item_over";overindex=this.getAttribute("index");};
				_div.onmouseout =  function(){this.className="search_item";overindex=this.getAttribute("index");};
			}
		}
	}
	_canvas.appendChild(frag);
	document.getElementById("searchinput").focus();

	if(p==0){
		_canvas.innerHTML= "<span>"+lg.nodata+"</span>";
	}
}

function selectSearchItem(username,userid){
	var node = document.getElementById("searchinput");
	node.value = username;
	node.setAttribute("presearvalue",username);

	GFRAME.selectUser(userid,true);
}

function rootItemStyle(){
	var _canvas = document.getElementById("searchListOutCanvas");
	var len =_canvas.childNodes.length-1;
	for(var i=len;i>=0;i--){
		_canvas.childNodes[i].className = "search_item";
	}
}

var overindex = 0;
function selectNextItem()
{
	var _canvas = document.getElementById("searchListOutCanvas");
	if(_canvas.firstChild.nodeName=="SPAN"){return;}
	if(overindex<_canvas.childNodes.length-1)
	{
		_canvas.childNodes[overindex].className = "search_item";
		overindex++;
		_canvas.childNodes[overindex].className = "search_item_over";
	}
	if(overindex>10){_canvas.scrollTop=(overindex-10)*18;}
	_canvas.childNodes[overindex].className = "search_item_over";
}

function selectPrevItem()
{

	var _canvas = document.getElementById("searchListOutCanvas");
	if(_canvas.firstChild.nodeName=="SPAN"){return;}
	if(overindex>0)
	{
		_canvas.childNodes[overindex].className = "search_item";
		overindex--;
		_canvas.childNodes[overindex].className = "search_item_over";
	}
	if(overindex>10){_canvas.scrollTop=(overindex-10)*18;}
	_canvas.childNodes[overindex].className = "search_item_over";
}

function selectOverItem()
{
	var _canvas = document.getElementById("searchListOutCanvas");
	if(_canvas.firstChild.nodeName=="SPAN"){return;}
	selectSearchItem(_canvas.childNodes[overindex].getAttribute("username"),_canvas.childNodes[overindex].getAttribute("userid"));

}
document.onkeydown = function(e){
	if(isSearchFocus)
	{
		var theEvent = window.event || e;
		var k  = theEvent.keyCode ? theEvent.keyCode : theEvent.which ? theEvent.which : theEvent.charCode;
		if(k ==40)
		{
			selectNextItem();
		}
		else if(k ==38)
		{
			selectPrevItem();
		}
		else if(k ==13)
		{
			selectOverItem();
		}
	}
};
function addGroupName(fm){
	var v = document.getElementById('addGroupNameInput').value;
	var re3 = new RegExp("[#,\'\"]");
	if(re3.test(v) || v.indexOf("'")>-1 || v.indexOf('"')>-1 || v.indexOf("\\")>-1){
		alert(top.lg.notspecial+" #,\',\",\\");
		return false;
	}
	if(v!=""){
		GFRAME.createNewGroup(v);
	}
	return false;
}

function showCustTree(){
	var img = document.getElementById("dotIcon");
	var treeIcon = document.getElementById("tree_icon");
	var url ='../';
	if(document.getElementById("custTreeLayer").style.display == "none"){
		GFRAME.isCustTreeShow  = true;
		treeIcon.setAttribute("src",url+"../images/ctree_title_03.jpg");
		img.innerHTML = lg.collspan;
	}else{
		GFRAME.isCustTreeShow  = false;
		treeIcon.setAttribute("src", url + "../images/ctree_title_04.jpg");
		img.innerHTML = lg.expand;
	}
	restFrame();
}

function hideenCustTree(){
	GFRAME.isCustTreeShow  = false;
	restFrame();
}
var haseChildSchoolBack = false;
function showSelectCustTitleBack(b){
	var mytitle = document.getElementById("myProlistTitle");
	var custtitle = document.getElementById("selectCustTitle");
	if(b){
		haseChildSchoolBack = true;
		mytitle.style.display = "none";
		custtitle.style.display = "block";
		showCustTree();
	}
}
//重新选择客户节点
GFRAME.selectCust = function(custid,deptShowName){
	 _('loading').style.display = "block";
	 //上一次选择客户已经执行完毕
		GFRAME.treeCustid = custid;
		var deptDiv = _("deptShowName_Div");
		var userListCanvas = _("userListCanvas");
		if(deptDiv)
			deptDiv.innerHTML = deptShowName;
		if(userListCanvas)
			userListCanvas.innerHTML = lg.fload;
		_.ajax.jsonp("../Handler/Handler.ashx?type=gz&sortid=" + custid + "&callback=GFRAME.selectCustBack");
};
//首次加载监控页面调用此函数
GFRAME.selectCustBack = function(obj) {
	GFRAME.listKey = null;
	GFRAME.listData = [];
	GFRAME.groupData = null;
	var deleteKeys = function(source){
		for(var index in source){
			var item = source[index];
			for(var key in item)
				delete item[key];
		}
	};
	//切换客户时清除相关数据，否则造成内存暴增
	deleteKeys([GFRAME.gropDivList,GFRAME.userList,GFRAME.userDivList]);
	if(obj&&obj.key){
		GFRAME.listKey = obj.key;
		GFRAME.listData = obj.records;
		GFRAME.groupData = groupVal.concat(obj.groups);
		setTimeout(function(){
			GFRAME.createGroup();
			GFRAME.buildDeviceList(obj.records);
		},0);
		setTimeout(function(){
			var readyInvoke = function(){
				var mapPage = _('map_frame').contentWindow;
				//可能loadMap还没有执行
				if(mapPage && mapPage.GFRAME && mapPage.GFRAME.map){
					mapPage.GFRAME.readyInvoke();
				}
				else{
					setTimeout(readyInvoke,100);
				}
			};
			readyInvoke();
		},120);
		//每一次切换客户时清除openid
		setOpenId(null);
		$('.addGroupBtn').show();
		_('loading').style.display = "none";
	}else{
		$('.addGroupBtn,#loading').hide();
		$('#friendGroupRightMenu').hide();
		_('allCountSpan').innerHTML = '0';
		_('onlineCountSpan').innerHTML = '0';
		_('offlineCountSpan').innerHTML = '0';
		_('userListCanvas').innerHTML = '';
		var mask = _('custIframeTree').contentWindow.document.getElementById('mask');
		if(mask)
			mask.style.display ='none';
	}
};
//根据是否显示在线和离线智能更新设备列表与marker的显示
GFRAME.updateByMenuState = function(online,offline){
	GFRAME.updateDeviceList(online,offline);
	_('map_frame').contentWindow.GFRAME.showMarkers(online,offline);
};
//更新左侧设备列表
GFRAME.updateDeviceList = function(showOnline,showOffline){
	if(!GFRAME.listKey)return;
	//刷新左边的用户列表
	GFRAME.resetUserListShow(showOnline,showOffline);
	//更新菜单数目
	GFRAME.updateGropUserViewCount(showOnline,showOffline);
	
	//更新报警数据
	GFRAME.getCarAlarmData();
	
};
//更新菜单设备数目以及菜单下的设备分组数目
GFRAME.updateGropUserViewCount = function(viewOnline,viewOffline) {
	var onlinesize = 0;
	var offlinesize = 0;
	for(var i=0;i<GFRAME.groupData.length;i++){
		var _gitem = GFRAME.gropDivList["G"+GFRAME.groupData[i].id];
		if(_gitem && _gitem.lastChild){
			var nodes = _gitem.lastChild.childNodes;
			var allcount = nodes.length;
			var onlinecount = 0;
			var offlinecount = 0;
			for(var j=0;j<allcount;j++){
				if(nodes[j].className.indexOf("online")>-1){
					onlinecount++;
					onlinesize++;
				}else{
					offlinecount++;
					offlinesize++;
				}
			}
			if(viewOnline&&viewOffline){
				_gitem.firstChild.lastChild.innerHTML = ' &nbsp; <span  style="font-weight:normal" >['+(onlinecount+offlinecount)+'/'+allcount+']</span>';
			}else{
				_gitem.firstChild.lastChild.innerHTML = ' &nbsp; <span  style="font-weight:normal" >['+(viewOnline?onlinecount:offlinecount)+'/'+allcount+']</span>';
			}
		}
	}
	_("onlineCountSpan").innerHTML = onlinesize;
	_("offlineCountSpan").innerHTML = offlinesize;
	_("allCountSpan").innerHTML = onlinesize + offlinesize;
};
//初始化设备列表
GFRAME.buildDeviceList = function(listdata){
	var onlinesize = 0, offlinesize = 0, i = 0 ,period = 1000*60*60*24*60, groupChildren = {},
		len = listdata.length, statusStr = lg.srun1+">60"+lg.d,
		isParent = isParentCt(), listKey = GFRAME.listKey, user_id = listKey.user_id;
	//为每一个组分配一个fragment
	for(var item in GFRAME.groupData){
		groupChildren['G'+GFRAME.groupData[item]['id']] = document.createDocumentFragment();
	}
	while(i < len){
		var node = listdata[i],	pojo = GFRAME.parseRecordPOJO(node);
		var run_status = ststus = pojo.run_status;
		if((node[listKey.server_time] - node[listKey.heart_time])> period  && node[listKey.su]!=-9  && run_status != lg.arrear && run_status.indexOf(lg.serviceEnd[0])<0 ){
			ststus = statusStr;
		}
		var _div = document.createElement("div"),
			frag = groupChildren['G'+node[listKey.group_id]] || groupChildren['G0'];
		frag.appendChild(_div);
		_div.setAttribute("userid", node[user_id]);
		_div.setAttribute("id", node[user_id]);
		_div.setAttribute("username", node[listKey.user_name]);
		_div.setAttribute("protype", node[listKey.product_type]);
		_div.style.display = 'block';
		//未上线和欠费设备不绑定事件
		if(pojo.run_status!=lg.arrear && node[listKey.su]!=-9){
			_div.onclick = selectDevice;
			_div.onmouseup = divMouseUp;
		}
		var str = ststus + '';
		if(isParent && pojo.show_charge){
			str += '<span class="help-ct"><a hideFocus="true" href="javascript:;" onmouseout="tipContent(this,false);" onmouseover="tipContent(this,true);">&nbsp;&nbsp;'+ lg.tax +'</a></span>';
		}
		_div.innerHTML = ['<div class="title" title="', node[listKey.user_name], '"><img width="16" height="16" src="../../images/',(pojo.online?'u_online':'u_offline'),'.gif" align="absmiddle"/>' ,
			node[listKey.user_name],'</div><div class="status" >' , str , '</div><div class="sudu">' , (pojo.su>0?pojo.su:0) ,'</div><div class="clear"></div>'].join('');

		if(pojo.online){
			_div.className = GFRAME.getOnlineClassName(pojo.run_status);
			onlinesize++;
		}else{
			_div.className="offline";
			offlinesize++;
		}
		GFRAME.userDivList['U'+node[user_id]] = _div;
		GFRAME.userList['U'+node[user_id]] = node;

		i++;
	}
	for(var groupId in groupChildren){
		//TODO IE 7在这里偶尔会报错
		try{
			GFRAME.gropDivList[groupId].lastChild.appendChild(groupChildren[groupId]);
		}catch(Ex){
			
		}
	}
	GFRAME.updateGropUserViewCount();
};
//点击左侧列表选择设备
function selectDevice(){
	var id = this.getAttribute("userid");
	GFRAME.selectUser(id);
}
var lastSelectUserTime = new Date();
//选择用户,鼠标双击放大地图
function divMouseUp(){
	var mapWin = _('map_frame').contentWindow;
	if(mapWin&&mapWin.GFRAME){
		if(new Date()-lastSelectUserTime<300) {
			mapWin.GFRAME.zoomIn(mapWin.GFRAME.openPopMarkerUid);
		}
		lastSelectUserTime = new Date();
	}
}

//获取报警信息
GFRAME.getCarAlarmData = function() {
    if (sn==undefined || sn=="") return;
    var seq = sn.join("|");
    var _uid = uid.join("|");
    var _gpsName = gpsName.join("|");
    $.ajax({
        type: "post",
        url: "../Handler/Handler.ashx?type=bj&sn=" + seq + "&uid=" + _uid + "&gpsname=" + escape(_gpsName) + "&date" + new Date(),
        success: function(data) {
            if (data != "") {
                document.getElementById("alarmInfoArea").innerHTML = data;
                play_click();
                AlarmClose("block"); //显示报警信息
            }
        }
    });
};
function AlarmClose(display) {
    document.getElementById("alarmInfoCanvas").style.display = display;
}

function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

//取消报警
function cancel(i, aMaker) {
    createXMLHttpRequest();
    try {
        aMaker.innerHTML = GTS.lang.s_TitleSubmitData;
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200 || xmlHttp.status == 0) {
                    if (xmlHttp.responseText == 'true') {
                        aMaker.innerText = "";
                        status = 1; //报警状态设置正常
                        $(aMaker).parent().parent().remove();
                    }
                }
            }
        };
        xmlHttp.open("GET", "../Handler/Handler.ashx?type=qxbj&id=" + i + "&date=" + new Date(), true);
        xmlHttp.send(null);
    } catch (exception) {
        alert(GTS.lang.s_TitleTerminalNotData + exception);
    }
}

//播放声音
function play_click() {
    var div = document.getElementById('alertDivInAllCarTrack');
    div.innerHTML = '<embed id="soundplayer" src="sound/ALARM.wav" loop="0" autostart="true" hidden="true"></embed>';
    var emb = document.getElementsByTagName('EMBED')[0];
    if (emb) {
        /* 这里可以写成一个判断 wav 文件是否已加载完毕，以下采用setTimeout模拟一下 */
        //setTimeout(function() { div.innerHTML = ''; }, 1000);
    }
}

//控制左边用户List的显示与隐藏，以及over选中，在线，离线，等文字状态
var sn=[],uid=[],gpsName=[];
GFRAME.resetUserListShow = function(showOnline,showOffline){
	var isParent = isParentCt(), selectUserId = getOpenId();
		listKey = GFRAME.listKey, user_id = listKey.user_id,
		online = "../../images/u_online.gif", 
		offline = "../../images/u_offline.gif",
		viewOnAndOff = showOnline&&showOffline,
		qfStr =  lg.arrear + '<span class="hp-ct"><a hideFocus="true" href="javascript:;" onmouseout="tipContent(this,false);" onmouseover="tipContent(this,true);">&nbsp;&nbsp;'+ lg.tax +'</a></span>',
		statusStr = lg.srun1+">60"+lg.d,
		period = 1000*60*60*24*60;
	//内部循环变量
	var node, pojo, ststus, run_status, item, qianfei, tl, st, su,len=GFRAME.userList.length;
	sn=new Array();uid=new Array();gpsName=new Array();
	for(var key in GFRAME.userList){
		node = GFRAME.userList[key];
        //过滤报警数据
        if (node[listKey.status] != "1" && node[listKey.status] != "3" && node[listKey.status] != "0") {
            sn.push(node[listKey.sim_id]);
            uid.push(node[listKey.user_id]);
            gpsName.push(node[listKey.user_name]);
        }
        
		pojo = GFRAME.parseRecordPOJO(node);
		ststus = run_status = pojo.run_status;
		item = GFRAME.userDivList["U"+node[user_id]];
		if(!item || item.children.length<1)
			continue;
		qianfei = (run_status == lg.arrear);
		tl = item.children[0]; st = item.children[1]; su = item.children[2];
		if((node[listKey.server_time] - node[listKey.heart_time])> period && node[listKey.su]!=-9  && run_status != lg.arrear && run_status.indexOf(lg.serviceEnd[0])<0 ){
			ststus = statusStr;
		}
		if(pojo.show_charge)
			ststus += ('<span class="help-ct"><a hideFocus="true" href="javascript:;" onmouseout="tipContent(this,false);" onmouseover="tipContent(this,true);">&nbsp;&nbsp;'+ lg.tax +'</a></span>');
		tl.setAttribute('qianfei',qianfei);
		tl.children[0].src = pojo.online ? online : offline;
		//1：更新左侧内容 只更新内容变化的地方,减少相同操作
		st.innerHTML = (isParent && qianfei)? qfStr : ststus;
		su.innerHTML = String(pojo.su>0 ?pojo.su:0);
		if(viewOnAndOff){
			item.style.display = 'block';
		}else{
			if(showOffline){
				item.style.display = pojo.online?'none':'block';
			}else if(showOnline)
				item.style.display = pojo.online?'block':'none';
		}
		if(selectUserId!=node[user_id])
			item.className = pojo.online?GFRAME.getOnlineClassName(pojo.run_status):'offline';
	}
};
//将用户移动到某个组
GFRAME.userMoveToGrop = function(groupid) {
	var userid = GFRAME.clickRightUserid;
	GFRAME.clickRightGroupid = groupid;
	var url ="GetGroupInfoService?method=moveUserToOtherGroup&user_id="+userid+"&group_id="+groupid+"&mds="+mds;
	_.ajax.jsonp(url+"&callback=GFRAME.userMoveToGropBack");
};
//将用户移动到某个组回调
GFRAME.userMoveToGropBack = function(obj) {
	if(obj.success){
		var userid = GFRAME.clickRightUserid;
		var groupid = GFRAME.clickRightGroupid;
		var _div = GFRAME.userDivList["U" + userid];
		GFRAME.gropDivList["G" + groupid].lastChild.appendChild(_div);
		GFRAME.updateGropUserViewCount();
	}else{
		alert(lg.moveGropFail);
	}
};
//收起或者展开组的内容
GFRAME.clickGroupName = function(groupid) {
	var _div = GFRAME.gropDivList["G" + groupid];
	if(_div.lastChild.style.display=="none") {
		_div.lastChild.style.display = "block";
		_div.firstChild.firstChild.innerHTML='<img src="../../images/g_o.gif" />';
	} else {
		_div.lastChild.style.display = "none";
		_div.firstChild.firstChild.innerHTML='<img src="../../images/g_c.gif" />';
	}
};

var lastSelectUserTime = new Date();
//选择用户
//设备列表移动到可视范围
GFRAME.movetoSelectUser = function(userid){
	var unode = GFRAME.userList["U"+userid];
	var item = GFRAME.userDivList["U"+userid];
	var o = item;
	//var groupdiv = GFRAME.gropDivList["G"+unode[GFRAME.listKey.group_id]];
	//groupdiv.lastChild.style.display = "block";

	var listCanvas = _("userListCanvas");
	//开始计算需要滚动的像素
	var v = item.getBoundingClientRect().top - listCanvas.getBoundingClientRect().top + listCanvas.scrollTop ;
	listCanvas.scrollTop = v-25;
};
//新建组回调
GFRAME.createNewGroupBack = function(obj) {
	if(obj.success) {
		var list = _("userListCanvas");
		_("addGroupNameFormCanvas").style.display="none";
		GFRAME.groupData.push({id:obj.groupID,name:createNewGroupOverName});
		var _div = document.createElement("div"),
			_g_name = document.createElement("div"),
			_g_canvas = document.createElement("div");

		list.appendChild(_div);
		_div.appendChild(_g_name);
		_div.appendChild(_g_canvas);
		_div.setAttribute("groupid",obj.groupID);
		GFRAME.gropDivList['G'+obj.groupID] = _div;

		_g_name.innerHTML = '<span style="padding-right:5px;"><img src="../../images/g_o.gif" /></span><span>'+createNewGroupOverName + '</span><span>[0]</span>';
		_g_name.className = "group_name";
		_g_name.onclick = function(){GFRAME.clickGroupName(this.parentNode.getAttribute("groupid"));};
		_g_name.onmouseover = GFRAME.rightClickGroupName;
		_g_canvas.className = "group_canvas";
		_("addGroupNameInput").value = "";
		
		list.scrollTop = list.scrollHeight;
		var addTips = _("successTips");
		addTips.innerHTML = lg.addGroupSuccess;
		addTips.style.display = "block";		
		setTimeout(function(){addTips.style.display = "none";},2000);
	} else {
		alert(lg.addGroupFail);
	}
};

var createNewGroupOverName = "";
//创建组
GFRAME.createNewGroup = function(groupname){
	createNewGroupOverName = groupname;
	var name = encodeURIComponent(groupname);
	var url = "/GetGroupInfoService?method=createGroup&callback=GFRAME.createNewGroupBack&school_id="+GFRAME.treeCustid+"&group_name="+name+"&remark="+name+"&mds="+mds;
	_.ajax.jsonp(url);
};
//显示组操作功能菜单
GFRAME.rightClickGroupName = function(){
	var t = $(this);
	var groupid = t.parent().attr("groupid");
	GFRAME.clickRightGroupid = groupid;
	GFRAME.clickRightGroupName = t.children().eq(1).html();
	var menu = $('#friendGroupRightMenu');
	var pos = t.offset();
	if(!$('.input_groupname','#userListCanvas').length && groupid != 0){
		menu.css({left: 185, top: pos.top + 5}).show();
	}else{
		menu.hide();
	}
};
//弹出更新组名称的输入框
GFRAME.modifyGroupName = function() {
	_('friendGroupRightMenu').style.display = 'none';

	if(GFRAME.clickRightGroupid!=0) {
		var gitem = GFRAME.gropDivList["G" + GFRAME.clickRightGroupid];
		var input_id = "input_group_name_"+GFRAME.clickRightGroupid;
		var v = gitem.firstChild.childNodes[1].innerHTML;
		gitem.firstChild.childNodes[1].innerHTML = '<input id="'+input_id+'" onblur="GFRAME.modifyGroupNameApp(this)" onkeydown="if(event.keyCode==13){GFRAME.modifyGroupNameApp(this);}"   type="text" groupid="'+GFRAME.clickRightGroupid+'" oldvalue="'+gitem.firstChild.childNodes[1].innerHTML+'" groupid="'+GFRAME.clickRightGroupid+'" class="input_groupname">';
		var ipt = _(input_id);
		if(ipt){ipt.focus();ipt.value = v;}
	}
};
//更新组名称
GFRAME.modifyGroupNameAppBack = function(obj) {
	if(obj.success) {
		for(var i=0;i<GFRAME.groupData.length;i++) {
			if(GFRAME.groupData[i].id==modifyGroupNameAppId){GFRAME.groupData[i].name=modifyGroupNameAppName;break;}
		}
		var gitem = GFRAME.gropDivList["G" + modifyGroupNameAppId];
		gitem.firstChild.childNodes[1].innerHTML = modifyGroupNameAppName;
	} else {
		alert(lg.reNameFail);
	}
};

var modifyGroupNameAppName = "";
var modifyGroupNameAppId = "";
//更新组名称回调
GFRAME.modifyGroupNameApp = function(_input) {
	var oldvalue = _input.getAttribute("oldvalue");
	var groupid = _input.getAttribute("groupid");
	modifyGroupNameAppName = _input.value;
	modifyGroupNameAppId = groupid;
	var re3 = new RegExp("[#,\'\"]");
	if(re3.test(_input.value) || _input.value.indexOf("'")>-1 || _input.value.indexOf('"')>-1 || _input.value.indexOf("\\")>-1){
		alert(lg.notspecial+" #,\',\",\\");
		return false;
	}
	if(oldvalue!=_input.value){
		var url = "/GetGroupInfoService?method=modifyGroupInfo&group_id="+groupid+"&group_name="+encodeURIComponent(_input.value)+"&remark=modify&mds="+mds;
		_.ajax.jsonp(url+"&callback=GFRAME.modifyGroupNameAppBack");
	}else{
		var gitem = GFRAME.gropDivList["G" + modifyGroupNameAppId];
		gitem.firstChild.childNodes[1].innerHTML = oldvalue;
	}
};
//删除组信息回调
GFRAME.deleteGroupBack = function(obj) {
	if(obj.success) {
		var gitem = GFRAME.gropDivList["G" + GFRAME.clickRightGroupid];
		var firstGitem = GFRAME.gropDivList.G0;
		for(var i=gitem.lastChild.childNodes.length-1;i>=0;i--) {
			firstGitem.lastChild.appendChild(gitem.lastChild.childNodes[i]);
		}
		var temp = GFRAME.groupData;
		GFRAME.groupData = [];
		for(var i=0;i<temp.length;i++) {
			if(temp[i].id!=GFRAME.clickRightGroupid){GFRAME.groupData.push(temp[i]);}
		}
		gitem.parentNode.removeChild(gitem);
		GFRAME.updateGropUserViewCount();
		var delTips = _("successTips");
		delTips.innerHTML = lg.delGroupSuccess;
		delTips.style.display = "block";
		_("friendGroupRightMenu").style.display = "none";
		setTimeout(function(){delTips.style.display = "none";},2000);
	} else {
		alert(lg.delGroupFail);
	}
};
//删除组信息
GFRAME.deleteGroup = function(){
	_('friendGroupRightMenu').style.display = 'none';
	if(confirm(lg.cfirm + lg.del + lg.groupName + " " + GFRAME.clickRightGroupName + " "+ lg.yes)){
		if(GFRAME.clickRightGroupid==0) {
			alert(lg.delDefault);
		} else {
			var url = "/GetGroupInfoService?method=deleteGroup&group_id="+GFRAME.clickRightGroupid+"&mds="+mds;
			_.ajax.jsonp(url+"&callback=GFRAME.deleteGroupBack");
		}
	}
};
function setPlaybackUrl(userid,link){
	link.href=link.getAttribute('data-url')+'&mapType='+GFRAME.currentMap+'&active_time='+utcToLocal(GFRAME.userList['U'+userid][GFRAME.listKey.datetime]).replace(/\//g,'-');
}
//工具条字符串拼接
GFRAME.writeToolBar = function(e,userid,username,protype,sn){
	GFRAME.clickRightUserid = userid;
	GFRAME.clickRightUsername = username;
	var strHtml =[];
	strHtml.push('<span><a target="_blank" href="' + trackUrl + escape(username) + '&objectid=' + userid + '&sn=' + sn + '" >' + GTS.lang.s_Title_CarTrack + '</a></span>|');
	strHtml.push('<span><a target="_blank" href="' + playbackUrl + escape(username) + '&random=' + GFRAME.treeCustid + '&objectid=' + userid + '&sn=' + sn + '">' + GTS.lang.s_Title_HistoryTrack + '</a></span>');
	if(GFRAME.treeCustid !== "1000003"){//屏蔽体验账号管理功能
		strHtml.push('<span class="more" style="display:none"><a href="javascript:;">'+lg.more+'</a>');
		strHtml.push('<div id="more" class="h3_cat" style="z-index:100;">');
		strHtml.push('<div class="shadow_border" style="width:120px">');
		strHtml.push('<ul style="text-align:left;width:120px;">');
		strHtml.push('<li><a href="javascript:;" onClick="GFRAME.viewProductInfo('+userid+')">'+lg.promanage+'</a></li>');
			if(GFRAME.groupData.length>0){
				strHtml.push('<li style="display:inline" class="group-ct"><a href="javascript:;">'+lg.moveGroup+'&gt;&gt;</a>');
				strHtml.push('<div id="group" class="h3_cat">');
				strHtml.push('<div class="shadow_border">');
					strHtml.push('<ul style="text-align:left">');
					for(var i=0;i<GFRAME.groupData.length;i++){
						strHtml.push('<li class="gitem"><a href="javascript:;" onclick="GFRAME.userMoveToGrop('+GFRAME.groupData[i].id+')">'+GFRAME.groupData[i].name+'</a></li>');
					}
					strHtml.push('</ul>');
				strHtml.push('</div>');
				strHtml.push('</div>');
				strHtml.push('</li>');
			}
			if(protype.indexOf("GT08") >-1||protype.indexOf("GT06") >-1||protype.indexOf("GT06S") >-1||protype.indexOf("GT06N") >-1||protype.indexOf("GM901") >-1||protype.indexOf("GT07") >-1||protype.indexOf("GT05A") >-1||protype.indexOf("GT05B") >-1||protype=="LY-H810"){
				strHtml.push('<li style="display:inline" class="msg"><a href="javascript:;">'+lg.zl+'&gt;&gt;</a>');
				strHtml.push('<div id="send-msg" class="h3_cat">');
				strHtml.push('<div class="shadow_border sendCmd">');
					strHtml.push('<ul style="margin:1px;text-align:left;">');
						strHtml.push('<li class="mitem"><a href="javascript:;" onClick="GFRAME.showSendCmdPage(\'CLOSE\')">'+lg.cutyd+'</a></li>');
						strHtml.push('<li class="mitem"><a href="javascript:;" onClick="GFRAME.showSendCmdPage(\'OPEN\')">'+lg.repyd+'</a></li>');
						strHtml.push('<li class="mitem"><a href="javascript:;" onClick="GFRAME.showSendCmdPage(\'POSITION\')">'+lg.checkp+'</a></li>');
						strHtml.push('<li class="mitem"><a href="javascript:;" onClick="GFRAME.showSendCmdPage(\'SEARCH\')">'+lg.checkr+'</a></li>');
					strHtml.push('</ul>');
				strHtml.push('</div></div></li>');
			}
//		strHtml.push("<li><a class='download' href='javascript:;' onclick='setTimeout(function(){if(win) win.openWinLayer(\""+
//				lg.downgj+"\",\"" + "/DownLoadKML.jsp?enterpriseID="+
//				GFRAME.treeCustid+"&selectedID="+userid + xdmKey +"\",600,450,2,window,null)},100)' >"+lg.downgj+"</a></li>");
		strHtml.push('</ul></div></div></span>');
	}
	return strHtml.join("");
};
//显示发送指令的界面
GFRAME.showSendCmdPage = function(code){
	var isDealer = "";
	if(GFRAME){isDealer="&isDealer=true";}
	var fatherId = _.url(location.href).params.fatherId || loginCustId;
	var qs = "&custid=" + fatherId + "&mds=" + mds + "&userid="+GFRAME.clickRightUserid+"&username="+
			encodeURIComponent(GFRAME.clickRightUsername)+isDealer+'&locale='+('cn'==lang?'zh-cn':'en-us');
	if(IS_CLIENT){
		qs += '&isClient=true';
	}
	if(code=="CLOSE") {//远程断油电
		setTimeout(function(){win.openWinLayer(lg.cutyd,jspDomain+"/user/sendProductCmd.jsp?code=CLOSE" + qs,
				300,200,2,window,null);},100);
	} else if(code=="OPEN") {//远程恢复油电
		setTimeout(function(){win.openWinLayer(lg.repyd,jspDomain+"/user/sendProductCmd.jsp?code=OPEN" + qs,
				300,200,2,window,null);},100);
	} else if(code=="POSITION") {//查询定位
		setTimeout(function(){win.openWinLayer(lg.checkp,jspDomain+"/user/sendProductCmd.jsp?code=POSITION" + qs,
				300,200,2,window,null);},100);
	} else if(code=="SEARCH") {//查询指令记录
		setTimeout(function(){win.openWinLayer(lg.checkr,jspDomain+"/user/sendProductCmdList.jsp?" + qs + 
				"&lang="+lang,700,400,2,window,null);},100);
	}
};
//查看产品详细资料
GFRAME.viewProductInfo = function(id) {
	setTimeout(function(){
		win.openWinLayer(lg.set,jspDomain
				+"/user/productDisplay.jsp?userid="+ (id || GFRAME.clickRightUserid) + xdmKey 
				+'&remote_url=&locale='+('cn'==lang?'zh-cn':'en-us'),
				500,400,2,window,null);
	},200);
};
//record单条数据 以及对应的KEY
GFRAME.parseRecordPOJO = function(record){
	var recObj = {};
	var getStaticArr = getStatic(record[GFRAME.listKey.datetime],record[GFRAME.listKey.server_time],
			record[GFRAME.listKey.sys_time],record[GFRAME.listKey.heart_time]);//获取停留货心跳时间
	var endServerTimeCount = -60*60*24*8;
	if(GLtax == "1"){
		endServerTimeCount = (parseInt(record[GFRAME.listKey.server_time],10) - parseInt(record[GFRAME.listKey.expire_date],10))/1000;
	}
	var _arr = status_(record[GFRAME.listKey.datetime], Number(record[GFRAME.listKey.su]), record[GFRAME.listKey.datetime], endServerTimeCount,parseInt(record[GFRAME.listKey.islac]));//_arr[0] = "gray";_arr[1] = "静止";_arr[2] = 0;
	if(record[GFRAME.listKey.weidu]=="" && record[GFRAME.listKey.jingdu]==""){
	    _arr=["gray",GTS.lang.s_Title_CarNoPosition,0,false];
	}
	
	var _dir = direction(_arr[2],record[GFRAME.listKey.iconType],record[GFRAME.listKey.hangxiang]);//direction[0] = "north";direction[1] = "北向";
	var _iconUrl = getIconURL(record[GFRAME.listKey.iconType],_arr[0],_dir);
	recObj.su = _arr[2];//运行速度//13
	recObj.hangxiang = getHangXiang(record[GFRAME.listKey.hangxiang],_arr[2]);//_dir[1];//行驶方向  "北向";//11
	recObj.iconUrl = this.imgUrl+_iconUrl;
	recObj.run_status = _arr[1];//运行状态//14
	recObj.online = _arr[3];
	if(parseInt(record[GFRAME.listKey.islac])==1){
	  if(GFRAME.crllist["C"+record[GFRAME.listKey.user_id]]!=undefined)
	   GFRAME.crllist["C"+record[GFRAME.listKey.user_id]].setCenter(new goome.maps.LatLng(parseFloat(record[GFRAME.listKey.weidu]),parseFloat(record[GFRAME.listKey.jingdu])));
	}
	recObj.show_charge = _arr[4];
	return recObj ;
};

GFRAME.circle=function(id){
   GFRAME.crllist[id] = new goome.maps.Circle({
     strokeColor: "#FF0000",
     strokeOpacity: 0.8,
     strokeWeight: 2,
	 fillColor: "#FF0000",
	 fillOpacity: 0.35,
	 center:new goome.maps.LatLng(22.57397818,113.92078757),
	 radius:200
  });
  GFRAME.crllist[id].setMap(GFRAME.map._source);
}


//获得用户列表在线用户的style ClassName
GFRAME.getOnlineClassName = function(status){
	var s = "online";
	if(status==lg.srun3){
		s = "online_green";//行驶
	}else if(status==lg.srun4){
		s = "online_orange";//快速行驶
	}else if(status==lg.srun5){
		s = "online_red";//超速行驶
	}
	return s;
};
//判断是否访问父窗体
function isParentCt(){
	return document.getElementById('tset_item') ? true :false;
}
//为选择设备添加样式
GFRAME.selectUser = function(userid,moveToView){
	if(!userid)return;
	var lastOpenId = getOpenId();
	var mapWin = _('map_frame').contentWindow,clearLock = false;
	//对选中的设备只做更新样式和显示操作栏
	$('#userListCanvas').find('div.itemonlineover').removeClass('itemonlineover').addClass('online').end()
	.find('div.itemofflineover').removeClass('itemofflineover').addClass('offline');
	var selectedRecord = GFRAME.userList["U" + userid];
	if(selectedRecord[GFRAME.listKey.weidu]=="" || selectedRecord[GFRAME.listKey.jingdu]==""){
          alert(GTS.lang.s_TitleTerminalNotData);return;
    } 
        
	var selectedItem = GFRAME.userDivList["U" + userid];
	if(selectedItem){
		var st = GFRAME.parseRecordPOJO(selectedRecord);
		if(st.online){
			selectedItem.className = 'itemonlineover';
		}else{
			selectedItem.className = "itemofflineover";
		}
		
		if(st && selectedItem && st.run_status != lg.arrear){
			$('.toolbar-ct','#userListCanvas').hide();
			var tbar = $('.toolbar-ct', $(selectedItem)); 
			if(tbar.length > 0){
				GFRAME.clickRightUserid = selectedItem.getAttribute("userid");
				GFRAME.clickRightUsername = selectedItem.getAttribute("username");					
				tbar.show();
				//选择了设备但自身没设置锁定时清除所有锁定
				if(GFRAME.lockTarget != GFRAME.clickRightUserid) 
					clearLock = true;				
			}else{
				showToolBar(selectedItem, GFRAME.writeToolBar(selectedItem, selectedItem.getAttribute('userid'), selectedItem.getAttribute('username'), selectedItem.getAttribute('protype'),selectedRecord[9]));
				clearLock = true;
			}
		}
		if(st.run_status == lg.srun1 || st.run_status.indexOf(lg.serviceEnd[0]) > -1){
			clearLock = true;
		}	
	}
	//是否移动左侧设备到可视范围
	if(moveToView)
		GFRAME.movetoSelectUser(userid);
	//如果上次选择marker不为空则关闭该marker，然后更新当前marker
	if(mapWin && mapWin.GFRAME){
		if(lastOpenId){
			mapWin.GFRAME.closeMarker(lastOpenId);
		}
		setOpenId(userid);
		mapWin.GFRAME.updateOpenMarker(userid,false);
		if(clearLock)
			mapWin.clearLock();
	}
};
//主菜选择菜单功能显示
function pageMenuShow(code,url){
	var codes = ["MORE","REP","HOME"];
	var nodes = document.getElementsByName('menuItem');
	var _div = document.getElementById("pageShowCanvas");
	var _monitor = document.getElementById("monitorCanvas");

	for(var i=0; i<codes.length; i++){
		if(code == codes[i]){
			//nodes[i].parentNode.className = "topmenuover";
			if(code == "HOME"){
				_div.style.display = "none";
				_monitor.style.left = "0";
			}else{
				var iframe = document.getElementById("pageShowFrame");
				var iframRight = document.getElementById("pageRight");
				var _height = document.documentElement.offsetHeight -
					document.getElementById("header").offsetHeight - 30;
					
			    var _width = (document.documentElement.offsetWidth)-parseInt(document.getElementById("divRight").style.width.toString().replace("px",""))-2;
				//iframe.setAttribute("src",url +'&locale='+ ((_CONFIG_.CONFIG_LANG=='cn')?'zh-cn':'en-us'));
				iframe.setAttribute("src",url);
				if(url.toString().indexOf("?cmd=e_m")!=-1){
				   url="Left_ActionExpand.aspx?url="+url+"&sortid="+GFRAME.treeCustid+"&tag=0";
				}else if(url.toString().indexOf("?cmd=e_p")!=-1){
				   url="Left_ActionExpand.aspx?url="+url+"&sortid="+GFRAME.treeCustid+"&tag=2";
				}else if(url.indexOf("?cmd=e_o")!=-1){
				   url="Left_ActionExpand.aspx?url="+url+"&sortid="+GFRAME.treeCustid+"&tag=3";
				}else if(url.indexOf("?cmd=server")!=-1){
				  url="Left_UserNothing.aspx";
				}else{
			       url="right1.aspx?url="+url+"&custid="+GFRAME.treeCustid;
				}   
				iframRight.setAttribute("src",url);
				iframe.style.height = _height + 'px';
				iframRight.style.height=_height+'px';
				document.getElementById("pageLeft").style.width=_width+"px";
				
				_div.style.display = "block";
				_monitor.style.left = "-9999em";
			}
		}else{
			//nodes[i].parentNode.className = "topmenu";
		}
	}
}
//更多中功能链接
function pageShowMore(url){
	document.getElementById("more_pop_up").style.display = 'none';
	var s = "custid=" + custid + "&remote_url=&updateUrl=" + 
	 "&id=" + custid+"&mds="+mds;
	url = url.indexOf("?") > -1 ? url : (url + "?");
	url = url.indexOf("=") > -1 ? (url + "&" + s) : url + s;
	pageMenuShow('MORE',url);
}

//显示加载进度条
function showTsetMenu(){
	var _m = document.getElementById("tset_menu");
	var _i = document.getElementById("tset_item");
	_m.className = "tset_menu_over";
	_i.className = "tset_item_over";
}

var hideTsetTimer = null;
function hideTsetMenu(){
	window.clearTimeout(hideTsetTimer);
	var app = function(){
		var _m = document.getElementById("tset_menu");
		var _i = document.getElementById("tset_item");
		_m.className = "tset_menu";
		_i.className = "tset_item";
	};
	hideTsetTimer = window.setTimeout(app,200);
}

function moveTsetMenu(){
	window.clearTimeout(hideTsetTimer);
}

function loadMessageCallBack(obj){
  $("#total").html(obj.total);
	//var logout = _('log_out');
//	$(logout.parentNode).after(isViewCust?'<div class="imenu"><a href="javascript:;"><var key="message"></var>(<span id="total">'+ obj.total +
//			'</span>)</a></div>':('<div class="imenu"><a href="javascript:;" onClick="pageShowMore(\''+ jspDomain + 
//			'/user/custCenterPassword.jsp?locale='+(lang=='cn'?'zh-cn':'en-us')+'\')">' + lg.server.ChangeLoginPassword +
//			'</a></div>'+((lang=='cn'&&!undefined)? '<div class="imenu"><a href="http://113.105.152.146:9010/helpClean.jsp?lang=cn&type=ECAR" target="_blank" class="bai">帮助</a></div>':'')+
//			'<div class="imenu"><a href="javascript:;" onClick="pageShowMore(\''+ jspDomain + 
//			'/user/custCenterMsglist.jsp?locale='+(lang=='cn'?'zh-cn':'en-us')+'\')">'+lg.server.message+'(<span id="total">' + obj.total + '</span>)</a></div>'));
}
//参数id为拖拽对象的id，handle为拖拽的手柄
function drag_top(self,e){
	var d_x,d_y,maxTop,minTop,top,y_h,oldH,drag_bar;//限定范围内拖动
	if(!document.getElementById('drag')){
		drag_bar = document.createElement('div');
		drag_bar.style.cssText ='border:2px dashed #666;position:absolute;top:27px;z-index:1000;width:255px;cursor:n-resize;display:none;';
		drag_bar.id="drag";
		$('#custTreeLayer').after($(drag_bar));
	}else
		drag_bar=document.getElementById('drag');

	minTop = 30;
	y_h=parseInt($("#custTreeLayer").css('height'));
	maxTop = $('#leftFrameCanvas').outerHeight()-120;
	drag_bar.style.height = y_h + 'px';
	oldH = $(self).position().top;
	$(self).addClass('move');
	$(self).css('top',oldH+'px');
	$(drag_bar).show();
	$('#drag_bar').show();

	e = e || window.event;
	d_y = e.clientY;

	$(document).bind('mousemove.mv',function(e){//mousemove.mv 事件命名，以便之后移除
		window.getSelection?window.getSelection().removeAllRanges():document.selection.empty();//阻止浏览器默认选取功能
		top = e.clientY - d_y;//移动增量
		d_x=(y_h+top)<minTop?minTop:(y_h+top)>maxTop?maxTop:(y_h+top);//判断拖拽的边界
		drag_bar.style.height = d_x+'px';
	}).bind('mouseup.mv',function(){//在document上面解除绑定mousemove，以免出现拖拽粘滞
		drag_bar.style.display='none';
		$(self).removeClass('move');
		document.getElementById('drag_bar').style.display='none';
		if(typeof d_x === 'number'){
			document.getElementById('custIframeTree').style.height=d_x-25+'px';
			document.getElementById('custTreeLayer').style.height=d_x+'px';
			document.getElementById('userListCanvas').style.height=maxTop-d_x+'px';
			window.frames['custIframeTree'].tree.setHeight(d_x-25);
		}
		$(document).unbind('mousemove.mv');
		$(document).unbind('mouseup.mv');
	});
}
//数据更新后刷新缓存
function reloadTreeRequest(parm){
	var p = "reloadTree";
	var urls ="";
	var i = 0;
	if((typeof parm)!="undefined"){
		p = "refreshCache&"+parm;
	}
	var AjaxRequest = function(){
		if(i<urls.length){
			$.ajax({type : "GET",dataType : "jsonp",jsonp: 'callback',url : urls[i]+p+"&mds="+mds,data :''});
			i++;
			setTimeout(AjaxRequest,1000);
		}
	};
	AjaxRequest();
}
//列表排序
function speedSortfn(type){
	$('div[groupid]','#userListCanvas').each(function(){
		var all = $(this).find('.group_canvas div[protype]'), data = [];
		all.each(function(i){
			data.push(this);
		}).remove();

		data.sort(function(a, b){
			if(type == "suSort"){
				return parseInt($(a).find('.sudu').text(),10) > parseInt($(b).find('.sudu').text(),10)  ?  -1 : 1;
			}else{
				return $(a).attr('username').localeCompare($(b).attr('username'));
			}
		});
		$(this).find('.group_canvas').append($(data));
		$('#sort-ct').hide();
		$("#userListCanvas").scrollTop(0);
	});
};
//显示操作栏位置
function showToolBar(e,ct){
	var ly = $('#custTreeLayer'), uc = $(document);
	var tb = $("<div class='toolbar-ct'>" + ct + "</div>");
	$('.more',tb).click(function(){
		var pos = $(this).position();
		var top = pos.top;
		if(top > uc.height()/2){
			top -= $('.h3_cat,.download',tb).length*8;
		}else{
			top += 30;
		}
		$('#more,#group',tb).hide();
		$('#friendGroupRightMenu').hide();
		$('#more',tb).css({top: top,left: pos.left}).show();
		return false;
	});

	$('.more,#more',tb).hover(function(){

	},function(){
		$('#more',tb).hide();
	});

	$('.group-ct',tb).hover(function(){
		if(document.all){
			var isShow = $('.msg',tb).is(':visible');
			var l = isShow ? 36 : 18;
			$('#group',tb).css({bottom: l}).show();
		}else{
			var pos = $(this).position();
			$('#group',tb).css({top: pos.top*3 - $('.gitem',tb).length*16}).show();
		}
	},function(){
		$('#group',tb).hide();
	});

	$('.msg',tb).hover(function(){
		if(document.all){
			$('#send-msg',tb).css({bottom: 18}).show();
		}else{
			var pos = $(this).position();
			$('#send-msg',tb).css({top: pos.top*2 - $('.mitem',tb).length*16}).show();
		}
	},function(){
		$('#send-msg',tb).hide();
	});

	$(e).append(tb);
}

//重置页面，IE 6-7隐藏头部会导致clientHeight的值变小，所以需要补上
function restFrame(topHeight){
	var _this = GFRAME;
	var mapWin = _('map_frame').contentWindow;
	var full = mapWin.document.getElementById('set_full_screen');
	var w = document.documentElement.clientWidth;
	var h = document.documentElement.clientHeight - _('header').clientHeight;
	if(_.isIE<8&&full&&full.checked)
		h+= 71;
	if(w<400){w=400;}
	if(h<300){h=300;}
	topHeight = parseFloat(topHeight) || 0;
	var _mapcanvas= mapWin.document.getElementById('mapcanvas'),
		_leftFrameCanvas = _("leftFrameCanvas"),
		_rightFrameCanvas = _("rightFrameCanvas"),
		_userListCanvas = _("userListCanvas"),
		_custTreeFrame = _("custIframeTree"),
		_custTreeLayer = _("custTreeLayer"),
		custTreeCanvasHeight = h - 385;
	var leftWidth = _leftFrameCanvas.style.display!='none'?_this.leftFrameWidth:0;
	_.css(_rightFrameCanvas,'width:'+(w - leftWidth - 26)+"px;height:"+(h-34)+'px;');
	_userListCanvas.style.height = (h - 153)+"px";
	var _h = _.isIE ? 58 : 60,fullMapHeight = h-_h + topHeight;
	_leftFrameCanvas.style.height = (h - 32) + "px";
	if(mapWin && _mapcanvas){
		var fullScreenNode = mapWin.document.getElementById('set_full_screen');
		if(fullScreenNode.checked){
			_.css(_mapcanvas,'z-index:10;position:absolute;left:3px;top:30px;*top:28px;width:'+(w-leftWidth-13)+'px;height:'+fullMapHeight+'px;');
		}else{
			_.css(_mapcanvas,'z-index:0;position:relative;left:0px;top:0px;width:'+(w -leftWidth-25)+'px;height:'+fullMapHeight+'px;');
		}
		setTimeout(function(){
			//此处设置宽度是为了防止地址过长影响地图布局，主要是影响ipad和智能手机
			var addr = mapWin.document.getElementById('overUserAddress');
			addr.style.width = (mapWin.document.documentElement.clientWidth - 380) +'px';
		},200);
	}
	if(custTreeCanvasHeight < 100) custTreeCanvasHeight = 100;
	if(_this.isCustTreeShow){
		_.css(_custTreeLayer,'height:20px;display:block;');
		if(_custTreeFrame.src != "null.html"){
			try{window.custIframeTree.tree.setHeight(custTreeCanvasHeight-45);}catch(e){}
		}
		var treeplay = function(){
			var height = (1 * custTreeCanvasHeight);
			_custTreeLayer.style.height = height+"px";
			if(height-45>0){
				_custTreeLayer.style.height = (height-20)+"px";
				_custTreeFrame.style.height = (height-20-25)+"px";
			}
			var ulistHeight = (h - 154 - (height-20));
			if(ulistHeight<10) ulistHeight=10;
			_userListCanvas.style.height = ulistHeight+"px";
			if(_custTreeFrame.src.indexOf("null.html")>-1){
				_custTreeFrame.src = (IS_CLIENT?"custTree.html?isDealer=": "custTree.jsp?isDealer=") +
						_this.isDealer + "&custid=" + _this.treeCustid +"&custname="+encodeURI(custname)+"&locale="+_.cookie('locale');
			}
		};
		treeplay();
	}else{
		_custTreeLayer.style.display = "none";
	}
}
//(初始化时)创建组信息
GFRAME.createGroup = function (){
	var userListCanvas = _("userListCanvas");
	userListCanvas.innerHTML = "";
	for(var i=0;i<GFRAME.groupData.length;i++){
		var _div = document.createElement("div"), _g_name = document.createElement("div"),
			_g_canvas = document.createElement("div");
		userListCanvas.appendChild(_div);
		_div.appendChild(_g_name);
		_div.appendChild(_g_canvas);

		_div.setAttribute("groupid",GFRAME.groupData[i].id);
		GFRAME.gropDivList["G"+GFRAME.groupData[i].id] = _div;
		_g_name.innerHTML = '<span style="padding-right:5px;"><img src="../../images/g_o.gif" /></span><span>'+GFRAME.groupData[i].name + '</span><span>0</span>';
		_g_name.className = "group_name";
		_g_name.onclick = function(){GFRAME.clickGroupName(this.parentNode.getAttribute("groupid"));};
		_g_name.onmouseover = GFRAME.rightClickGroupName;
		_g_canvas.className = "group_canvas";
	}
};
//隐藏与显示左侧设备列表,在iframeload以后才进行绑定，否则会获取不到iframe
function bindToggleDeviceList(){
	 var minToogle = _('toogle_min'),maxToogle = _('toogle_max');
	 $(minToogle).hover(function(){
		 this.style.backgroundPosition='100% 0';
	 },function(){
		 this.style.backgroundPosition='68% 0';
	 }).click(function(){
		 $(this).hide();
		 $("#toogle_max").show();
		 var left = $("#leftFrameCanvas");
		 left.show();
		 var width = (document.documentElement.clientWidth-13-268)+'px';
		 $('#rightFrameCanvas').css({width:width});
		 _('map_frame').contentWindow.document.getElementById('mapcanvas').style.width = width;
	 });
	 $(maxToogle).hover(function(){
		 this.style.backgroundPosition='0 0';
	 },function(){
		 this.style.backgroundPosition='35% 0';
	 }).click(function(){
		 $(this).hide();
		 $("#toogle_min").show();
		 $("#leftFrameCanvas").hide();
		 var width = (document.documentElement.clientWidth-13)+'px';
		 $('#rightFrameCanvas').css({width:width});
		 _('map_frame').contentWindow.document.getElementById('mapcanvas').style.width = width;
	 });
}
function getParentMsgCallBack(obj){
	var StrHtml = [];
	if(obj.success){
		StrHtml.push('<div>'+lg.ServerProvider+' : '+obj.data.name+'<img style="position:absolute;top:-8px;right:-5px;" width="12" height="12" onclick="$(this).parent().parent().attr(\'className\',\'tset_item\')" src="../images/close.gif"></div>');	
		StrHtml.push('<div>'+lg.contact+' : '+obj.data.contact+'</div>');
		StrHtml.push('<div>'+lg.phone+' : '+obj.data.phone+'</div>');
		StrHtml.push('<div>'+lg.address+' : '+obj.data.addr+'</div>');
		$("#tset_item").html(StrHtml.join(""));
	}
}
function validateInfo(ret){
	if(ret&&ret.data){
		if(!ret.data.contact || !ret.data.phone){
			$('body').append('<div style="position:absolute;top:5px;left:400px;background-color:yellow;color:#333;padding:4px 6px;">' + 
				 lg.completeInfoTip + '<a style="margin-left:10px;" href="javascript:;" onclick="pageShowMore(jspDomain+\'/user/custCenter.jsp?mds=\'+mds)">'+
				 lg.complete + '</a><span style="margin:0 5px;">|</span><a href="javascript:;" onclick="_.dom.remove(this.parentNode);">'+
				 lg.clos + '</a></div>');
		}
	}
}
//首次请求加载设备信息，请求成功以后发起后续请求。这里使用_.ajax.getScript而不是_.ajax.jsonp，否则会存在请求同时发出的竞用
_.ajax.getScript("../Handler/Handler.ashx?type=gz&sortid=" + GFRAME.treeCustid + "&callback=GFRAME.selectCustBack",function(){
	//客户树
	_.ajax.getScript("../Handler/Handler.ashx?type=haveChildSchool&schoolId="+GFRAME.treeCustid+"&callback=showSelectCustTitleBack&mds="+mds,function(){
		 //报警信息，对经销商的判断有依赖haseChildSchoolBack
		 _.ajax.getScript('../js/warns.js?v=',function(){
			// window.timeWarnOBJ = new WarnsTimely(custid,"",mds,"",loginUrl);
			 _.net.backup(
				 {context:timeWarnOBJ,name:'loadDataById'},
				 {context:timeWarnOBJ,name:'loadDataCallBack'},
				 {
					server:"",
					backupServer:"",
					serverImg:""
				 }
			 );
//			if("1" == warnFlag)
//				timeWarnOBJ.timer(27000);
		 });
	});
	//未读消息
	setTimeout(function(){
		 _.ajax.getScript('../Handler/Handler.ashx?type=getUnreadMsgNum&school_id='+custid+'&mds='+
			 mds+'&callback=loadMessageCallBack');
	 }, 2000);
	//经销商信息,getEnterpriseByID==>pid or getSuperContactInfo==>loginCustId
	 if(pid!="0"){
		 setTimeout(function(){
			 _.ajax.getScript("../Handler/Handler.ashx?type=getSuperContactInfo&callback=getParentMsgCallBack&id="+loginCustId+"&mds="+mds);
		 }, 2000);
	 }
	 
});
window.onresize = function(){
	restFrame();
};
(function() {
    _('map_frame').src = '../../../MainMap/main_files/map.aspx?v=';
    //$('#username').html(username||'');
    $('#custname,#deptShowName_Div').html(custname || '');
    $('#searchinput').val(lg.server['addGroupTip']);
    $('#confirm_add_group').val(lg.server['checkAdd']);
    var logout = document.getElementById('log_out');
    var logOutUrl = _.url(location.href).params.logOut;
    //	if(!IS_CLIENT){
    $(logout).attr('href', 'javascript:;').click(function() {
        if (confirm(GTS.lang.s_Title_ConfirmExit))
            top.location = "../Quit.aspx?language=" + lang;
    });
    //	}else{

    //	}
    //设置图片路径
    if (pid != 0) {
        $('#tset_menu').html('<a><img src="../../images/user.gif" style="padding-top:5px;*padding-top:0;_padding-top:4px;" width="16" height="16" title="ServerProvider" /><small style="color:gray;font-size:10px">▼</small></a>');
        $('#tset_item').html('<img  src="../../images/loading.gif" width="16" height="16" />&nbsp;' + lg.server.Loading + '&nbsp;');
    }
    //treeicon
    $('#tree_icon').attr('src', '../../images/ctree_title_03.jpg');
    //
    $('#custTreeLayer').children().eq(1).html('<img src="../../images/tree_uclose_03.jpg" />');
    //监控、统计相互切换
    $('#goto_report').click(function() {
        pageMenuShow('REP', 'reports/report.jsp?enterprise_id=' + window.custid);
    });
    $('#goto_monitor').click(function() {
        pageMenuShow('HOME', null);
    });
    //顶部更多菜单
    var info = $('#more_info');
    $('.pop_up').hover(function() {
        $(this).show();
    }, function(e) {
        $(this).hide();
    });
    info.hover(function() {
        $('.pop_up').css({ left: info.offset().left, top: info.offset().top + info.height() }).show();
    }, function() {
        $('.pop_up').hide();
    });

    //速度名称排序
    $(".sort-wrap a").click(function() {
        speedSortfn(this.id);
        return false;
    });
    $('.sort-wrap').hover(function() {
        $('.sort-wrap').addClass('hover-sort');
        $('#sort-ct').show();
        $('#friendGroupRightMenu').hide();
    }, function(e) {
        $('.sort-wrap').removeClass('hover-sort');
        $('#sort-ct').hide();
    });
    //组管理菜单
    $('#friendGroupRightMenu').html('<a href="javascript:GFRAME.modifyGroupName();" hideFocus="true">' + lg.server.edit +
			'</a><a href="javascript:GFRAME.deleteGroup();" hideFocus="true" style="margin-left:5px;" >' + lg.server.delGroup + '</a>');
    //隐藏创建组输入框
    $(document).click(function(e) {
        var t = $(e.target);
        if (t.attr('className') != 'addGroup' && !t.parents('.GroupNameFormCanvas').length &&
				$('#addGroupNameFormCanvas:visible').length > 0) {
            $('#addGroupNameFormCanvas').hide();
        }
        if (t.attr('className') != 'suggest' && t.attr('className') != 'searchinput' &&
				$('#searchListOutCanvas:visible').length > 0) {
            $('#searchListOutCanvas').hide();
        }
        $('#friendGroupRightMenu').hide();
    });
    //移动显示组操作栏
    $('#userListCanvas').scroll(function() { $('#more,.tipContent,#searchListOutCanvas,#addGroupNameFormCanvas,#friendGroupRightMenu').hide(); });
    if (pid != 0) {
        var ifrTree = document.getElementById('custIframeTree');
        ifrTree.src = "../../../MainMap/main_files/CustTree.aspx?custid=" + custid + "&custname=" + custname + "&pid=" + pid;
    } else {
        document.getElementById("selectCustTitle").style.display = "none";
    }

    //var logoPath;
    // alert(document.getElementById("selectCustTitle"));
    //	 if(IS_CLIENT){
    //		 var locDomain = _.cookie('LOCAL_DOMAIN');
    //		 var logoUrl = _.cookie('LOCAL_LOGO_URL');		 
    //		 logoPath = (logoUrl ? 'Res' : '') || (locDomain ? ('/local/' + locDomain) : '') || '/user/';
    //	 }else{
    //		 logoPath = LOCAL_LOGO_URL || '/user/';
    //	 }
    //	//下载cs链接
    //	 if(!IS_CLIENT&&!IS_LOCAL){
    //		if('cn'==lang){
    //			$('#download_div').html('<table style="border-spacing:0;"><tr><td><div style="margin-left:6px;"><b>下载车辆监控</b>\<a target="_blank" style="color:#fff;" href="http://download.gpsoo.net/gpsoo/client/车辆监控.exe"><img src="' +
    //					_CONFIG_.STATIC_SITE + '/images/download.png" style="width:15px;height:15px;margin-top:4px;" />exe</a><b style="color:#bbb;margin:0 2px;">|</b><a target="_blank" style="color:#fff;" href="http://download.gpsoo.net/gpsoo/client/车辆监控.zip"><img src="' +
    //					_CONFIG_.STATIC_SITE+'/images/download.png" style="width:15px;height:15px;margin-top:4px;" />zip</a></div></td></tr></table>');
    //		}else{
    //			$('#download_div').html('<table style="border-spacing:0;"><tr><td><div style="margin-left:6px;"><b>Download Easy Track Platform:</b>\<a target="_blank" style="color:#fff;" href="http://download.gpsoo.net/gpsoo/client/' +
    //					'easy-track-platform.exe"><img src="' + _CONFIG_.STATIC_SITE + 
    //					'/images/download.png" style="width:15px;height:15px;margin-top:4px;" />exe</a><b style="color:#bbb;margin:0 2px;">|</b><a target="_blank" style="color:#fff;" href="http://download.gpsoo.net/gpsoo/client/easy-track-platform.zip"><img src="' + 
    //					_CONFIG_.STATIC_SITE+'/images/download.png" style="width:15px;height:15px;margin-top:4px;" />zip</a></div></td></tr></table>');
    //		}
    //}
    //设置含有背景图片的元素样式
    //	 _.css.append(['body{background:url(','../images/index_new_04.jpg' + ') repeat-x;}.navigate_item{background:url(',
    //		'/dealer/images/navigate_item_bg.gif) repeat-x;}.navigate_item_over{background:url(',
    //		'/dealer/images/navigate_select_item_bg.gif) repeat-x;}a.statemenu:link,a.statemenu:visited,a.statemenu:hover,a.statemenu:active{background-image:url(',
    //		'/user/images/logo_07.jpg);}.suggest{background:url(',
    //		'/user/images/productsearch_03.jpg) no-repeat bottom;}.expand{background-image:url(',
    //		'/user/images/tree_uclose_03.jpg) center no-repeat;}.h2_cat{background-image:url(',
    //		'/user/images/null.gif);}.min-left_default_r{background-image:url(',
    //		'/user/images/mini-left.gif);}.min-left_default_l{background-image:url(',
    //		'/user/images/mini-left.gif);}.hover_tips .hover_tips_zt, .hover_tips .hover_tips_ztb{background: url(',
    //		'/dealer/images/tips_icon.png) no-repeat scroll -21px 0 transparent;}.topmenu{background-image:url(' ,
    //		'/user/images/index_new_15.jpg);}.topmenuover{background-image:url(',
    //		'/user/images/index_new_13.jpg);}'].join(""));
    //弹窗对象
    // _.ajax.getScript('../js/dialog.v2.js?v=',function(){
    // 	win = new Dialog({borderColor:'#c1c1c1'});
    // });

    //验证信息是否完整
    // _.ajax.jsonp( '../Handler/Handler.ashx?type=getEnterpriseByID&callback=validateInfo&id='+loginCustId+'&mds='+mds);
})();